// 连接 websocket 服务端
const ws = new WebSocket('ws://localhost:8001/');

function output(msg, type = 'client') {
    const mlistDiv = document.querySelector('.message-list')
    const mitem = document.createElement('li')
    mitem.className = `message-item ${type}`
    mitem.textContent = msg
    mlistDiv.appendChild(mitem)
}

ws.onopen = () => {
    console.log('连接成功');
    
    // 发送消息
    // ws.send('hello');
    // msgList.forEach((msg, i) => {
    //     setTimeout(() => {
    //         ws.send(msg)
    //         console.log('客户端发送消息:', msg);
    //         output(msg, 'client')
    //     }, i * delay * 1000)
    // })
}

ws.onmessage = async (e) => {
    // console.log(e.data); // Blob
    const msg = e.data?.text ? await e.data.text() : e.data
    console.log('客户端收到:', msg); // Blob
    output(msg, 'server')
}

ws.onclose = () => {
    console.log('连接关闭');
}

ws.onerror = () => {
    console.log('连接出错');
}

function sendMessage() {
    const msgInput = document.querySelector('.input-message')
    const msg = msgInput.value
    if (msg) {
        ws.send(msg)
        output(msg, 'client')
        msgInput.value = ''
    } else {
        alert('请输入消息')
    }
}


function init() {
    const sendBtn = document.querySelector('#send-btn')
    sendBtn.addEventListener('click', sendMessage)

    const msgInput = document.querySelector('.input-message')
    msgInput.addEventListener('keyup', (event) => {
        if (event.key === 'Enter') {
            sendMessage()
        }
    })
}

document.addEventListener('DOMContentLoaded', init)
// init();

